<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-calendar"></i> 学院基本信管理
        </el-breadcrumb-item>
        <el-breadcrumb-item>学院编辑</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="form-box">
        <el-form ref="formRef" :rules="rules" :model="form" label-width="80px">
          <el-form-item label="物品名称" prop="goodsName">
            <el-input v-model="form.goodsName" aria-required="true"></el-input>
          </el-form-item>
          <!--             :file-list="fileList"-->
          <el-form-item label="图片样例" prop="collegeName">
            <el-upload ref="pictureUpload" action="#" list-type="picture-card"
                       :limit="4" :on-exceed="handleExceed"
                       :auto-upload="false"
                       :file-list="fileList"

                       :on-change="handleFile">
              <template #default>
                <i class="el-icon-plus"></i>

              </template>
              <template #file="{ file }">
                <div>
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""/>
                  <span class="el-upload-list__item-actions">
          <span
              v-if="!disabled"
              class="el-upload-list__item-delete"
              @click="handleRemove(file)"
          >
            <i class="el-icon-delete"></i>
          </span>
        </span>
                </div>
              </template>
            </el-upload>

          </el-form-item>
          <el-form-item label="物品类型" prop="goodsType">
            <el-input v-model="form.goodsType" placeholder="床上用品或军训用品" aria-required="true">></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">提交</el-button>
            <!--            <el-button @click="onReset">重置</el-button>-->
          </el-form-item>
        </el-form>

      </div>
    </div>
  </div>
</template>
<script>
import {reactive, ref} from 'vue'
import {ElMessage} from "element-plus";
import request from "../../utils/request";
import {useRoute, useRouter} from "vue-router";
import {useStore} from "vuex";

export default {
  name: "AddCollege",
  methods: {
    //文件上传
    submitUpload() {
      this.$refs.upload.submit();
    },
    //文件数量控制
    handleExceed(files, fileList) {
      console.log(fileList)
      this.$message.warning(
          `The limit is 1, you selected ${
              files.length
          } files this time, add up to ${files.length + fileList.length} totally`
      );
    },
    //文件移除
    handleRemove(file) {
      let uploadFiles = this.$refs.pictureUpload.uploadFiles
      for (var i = 0; i < uploadFiles.length; i++) {
        if (uploadFiles[i]['url'] == file.url) {
          uploadFiles.splice(i, 1)
          this.fileList.splice(i, 1)
          console.log(this.fileList)
        }
      }
    },
  },
  setup() {
    const root = "/goods/";
    const router = useRouter();
    const route = useRoute();
    const store = useStore();
    const dialogImageUrl = ref("")
    const dialogVisible = ref(false)
    const disabled = ref(false)
    const importVisible = ref(false)
    const formData = new FormData();
    const formRef = ref(null);

    const form = reactive({
      sid: "",
      goodsName: "",
      goodsType: "",
    });
    // http-request上传图片
    const submitUploadET = (params) => {
      formData.append("files", params.file)
      console.log(formData.getAll('files'))
    };
    const handleFile = (file, fileList) => {
      console.log(fileList)
      formData.delete("files")
      for (var i = 0; i < fileList.length; i++) {
        console.log(fileList[i])
        formData.append("files", fileList[i].raw);
      }
      console.log(formData.getAll("files"))
    };
    // 提交
    const onSubmit = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          // 表单校验
          formData.append("goodsName", form.goodsName);
          formData.append("goodsType", form.goodsType);
          console.log(formData)
          if (form.sid) {
            if (fileList.value != null && fileList.value.length > 0) {
              for (var i = 0; i < fileList.value.length; i++) {
                formData.append("urls", fileList.value[i].url);
              }
            }
            formData.append("sid", form.sid);
            request.post("/goods/updateGoods", formData, {
              headers: {"Content-Type": "multipart/form-data"},
            }).then((res) => {
              if (res.code !== null) {
                ElMessage.error(res.msg);
              } else {
                ElMessage.success("提交成功！");
                formData.delete("goodsName");
                formData.delete("goodsType");
                // 关闭当前页面的标签页;
                store.commit("closeCurrentTag", {
                  $router: router,
                  $route: route,
                });
                router.push("/admin/goods");
              }
            });
          } else {
            request.post("/goods/insertGoods", formData, {
              headers: {"Content-Type": "multipart/form-data"},
            }).then((res) => {
              if (res.code !== null) {
                ElMessage.error(res.msg);
              } else {
                ElMessage.success("提交成功！");
                formData.delete("goodsName");
                formData.delete("goodsType");
                // 关闭当前页面的标签页;
                store.commit("closeCurrentTag", {
                  $router: router,
                  $route: route,
                });
                router.push("/admin/goods");
              }
            });
          }
        } else {
          return false;
        }
      });
    };
    // 重置
    const onReset = () => {
      formRef.value.resetFields();
    };
    const fileList = ref([]);
    if (route.query.id) {
      request.get(root + route.query.id).then((res) => {
        form.sid = route.query.id;
        form.goodsName = res.data.goodsName;
        form.goodsType = res.data.goodsType;
        var tadate = [];
        tadate = res.data.goodsUrl.split(',')
        for (var i = 0; i < tadate.length; i++) {
          var file = {
            name: "",
            url: ""
          }
          file.name = tadate[i].substring(tadate.indexOf("uploadfile/"), tadate[i].length)
          file.url = tadate[i]
          if (file.name != null && file.name.length > 0 && file.url != null && file.url.length > 0) {
            fileList.value.push(file)
          }
        }
        console.log(fileList.value)

      });
    }
    const rules = {
      goodsName: [
        {required: true, message: "请输入物品名", trigger: "blur"},
      ],
      goodsType: [
        {required: true, message: "请输入物资另类型", trigger: "blur"},
      ],
    };

    return {
      rules,
      form,
      dialogVisible,
      dialogImageUrl,
      disabled,
      importVisible,
      handleFile,
      onSubmit,
      formRef,
      submitUploadET,
      onReset,
      fileList,
      formData,

    };
  }

}

// export default {
//   name: "AddGoods",
//   data() {
//     return {
//       dialogVisible: false,
//       form: {
//         goodsName: "",
//         goodsType: ''
//       }
//     }
//   },

// methods: {
//   handleRemove(file) {
//     console.log(file);
//   },
//   handlePictureCardPreview(file) {
//     this.dialogImageUrl = file.url;
//     this.dialogVisible = true;
//   },
//   handleDownload(file) {
//     console.log(file);
//   }
// }
</script>

<style scoped>

</style>